﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DatabaseHelper;

namespace TestUI
{
    public partial class DBHelperTest : Form
    {
        DBHelper dh = new DBHelper();
        BindingSource bds = new BindingSource(); // For data binding
        DataTable dt = new DataTable(); // For data binding
        Random rand = new Random(); // Use to generate random number
        string[] strRand = new string[6]; // Random number as string

        public DBHelperTest()
        {
            InitializeComponent();
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            dh.Query = "SELECT * FROM Events";
            // 
            dt = dh.Fill();
            bds.DataSource = dt;
            dgvEvents.DataSource = bds;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            dh.Query = "SELECT * FROM Events";
            // Save to database
            dh.Update(dt);
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < 6; i++)
            {
                strRand[i] = rand.Next(1000).ToString();
            }
            UpdateBox();
            dh.Add(NewEvent(),"2");

            // Update datagridview. 
            // This method will be add in the TreeListView User Control
            dh.Query = "SELECT * FROM Events";
            dt = dh.Fill();
            bds.DataSource = dt;
            dgvEvents.DataSource = bds;
        }

        // Create new evenet
        private PEvent NewEvent()
        {
            PEvent e = new PEvent();
            e.KP = strRand[0];
            e.Easting = strRand[1];
            e.Northing = strRand[2];
            e.Description = strRand[3];
            e.GeneralComment = strRand[4];
            e.Comment = strRand[5];
            return e;
        }

        // Update the text boxes and combo boxes
        private void UpdateBox()
        {
            txtKP.Text = strRand[0];
            txtEasting.Text = strRand[1];
            txtNorthing.Text = strRand[2];
            cbbDescription.Text = strRand[3];
            cbbGeneralComment.Text = strRand[4];
            cbbComment.Text = strRand[5];
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (dgvEvents.SelectedRows.Count > 0)
            {
                foreach (DataGridViewRow item in dgvEvents.SelectedRows)
                {
                    dgvEvents.Rows.RemoveAt(item.Index);
                }
            }
            else
            {
                MessageBox.Show("No row is deleted. Please select.");
            }
        }
    }
}
